<template>
    <el-card shadow="never" class="page-card" v-loading="loading">
        <div class="detail-header">
            <el-button @click="goBack" icon="el-icon-arrow-left" size="large" class="mr-2">返回</el-button>
            <h2 class="detail-title">{{ route.query.planName }}</h2>
        </div>
        <div class="filter-bar">
            <el-select v-model="status" placeholder="考核状态" class="mr-2" size="large" @change="handleStatusChange">
                <el-option label="全部" value="" />
                <el-option label="评分中" value="inProgress" />
                <el-option label="已完成" value="completed" />
            </el-select>
            <el-input v-model="search" placeholder="请输入关键字" prefix-icon="el-icon-search" class="search-input"
                size="large" clearable @input="handleSearch" />
            <el-button type="primary" class="ml-2" size="large" @click="handleBatchTerminate" :disabled="!selectedRows.length">批量终止考核</el-button>
        </div>
        <el-table :data="filteredEmployees" class="mt-2" border stripe @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="name" label="被考核员工" />
            <el-table-column prop="deptName" label="员工部门" />
            <el-table-column prop="type" label="员工职位" />
            <el-table-column prop="assessmentStatus" label="考核状态">
                <template #default="scope">
                    <el-tag :type="scope.row.assessmentStatus === '已完成' ? 'success' : 'warning'">
                        {{ scope.row.assessmentStatus }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
                <template #default="scope">
                    <el-link type="primary" @click="goEmployeeDetail(scope.row.id, scope.row.name, scope.row.assessmentStatus)">查看详情</el-link>
                    <el-link type="danger" class="ml-2" @click="handleTerminate(scope.row)" v-if="scope.row.assessmentStatus === '评分中'">终止考核</el-link>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination-bar">
            <el-pagination 
                background 
                layout="total, sizes, prev, pager, next, jumper" 
                :total="total"
                :page-size="pageSize"
                :current-page="currentPage"
                :page-sizes="[10, 20, 50, 100]"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                class="mt-2" 
            />
        </div>
    </el-card>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { get, update } from '@/api/jixiao/assessmentProgress/detail.js'
import { ElMessage, ElMessageBox } from 'element-plus'

const route = useRoute()
const router = useRouter()
const status = ref('')
const search = ref('')
const loading = ref(false)
const employees = ref([])
const selectedRows = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 过滤后的员工列表
const filteredEmployees = computed(() => {
    let result = employees.value
    
    // 状态过滤
    if (status.value) {
        result = result.filter(emp => emp.assessmentStatus === status.value)
    }
    
    // 搜索过滤
    if (search.value) {
        const keyword = search.value.toLowerCase()
        result = result.filter(emp => 
            emp.name.toLowerCase().includes(keyword) ||
            emp.deptName.toLowerCase().includes(keyword) ||
            emp.type.toLowerCase().includes(keyword)
        )
    }
    
    return result
})

// 获取列表数据
async function fetchList() {
    if (!route.query.id) return // 如果没有ID参数，不执行请求
    
    loading.value = true
    try {
        const res = await get({ 
            departmentId: route.query.id, 
            assessmentStatus: status.value,
            pageNum: currentPage.value,
            pageSize: pageSize.value
        })
        employees.value = res.rows
        total.value = res.total
    } catch (error) {
        ElMessage.error('获取数据失败')
    } finally {
        loading.value = false
    }
}

// 监听路由参数变化
watch(
    () => route.query.id,
    (newId, oldId) => {
        if (newId !== oldId) {
            // 重置分页和筛选条件
            currentPage.value = 1
            status.value = ''
            search.value = ''
            // 重新获取数据
            fetchList()
        }
    },
    { immediate: true }
)

// 处理状态变更
function handleStatusChange() {
    currentPage.value = 1
    fetchList()
}

// 处理搜索
function handleSearch() {
    currentPage.value = 1
    fetchList()
}

// 处理分页大小变更
function handleSizeChange(val) {
    pageSize.value = val
    fetchList()
}

// 处理页码变更
function handleCurrentChange(val) {
    currentPage.value = val
    fetchList()
}

// 处理表格选择
function handleSelectionChange(selection) {
    selectedRows.value = selection
}

// 处理单个终止考核
async function handleTerminate(row) {
    try {
        await ElMessageBox.confirm('确定要终止该员工的考核吗？', '提示', {
            type: 'warning'
        })
        await update({ id: row.employeeAssessmentDetailId, assessmentStatus: "已完成" })
        ElMessage.success('终止考核成功')
        fetchList()
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('操作失败')
        }
    }
}

// 处理批量终止考核
async function handleBatchTerminate() {
    if (!selectedRows.value.length) {
        ElMessage.warning('请选择要终止考核的员工')
        return
    }
    
    try {
        await ElMessageBox.confirm(`确定要终止选中的 ${selectedRows.value.length} 名员工的考核吗？`, '提示', {
            type: 'warning'
        })
        
        const promises = selectedRows.value.map(row => 
            update({ id: row.employeeAssessmentDetailId, assessmentStatus: "已完成" })
        )
        
        await Promise.all(promises)
        ElMessage.success('批量终止考核成功')
        fetchList()
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('操作失败')
        }
    }
}

function goBack() {
    router.back()
}

function goEmployeeDetail(id, employeeName, assessmentStatus) {
    router.push({ 
        name: 'personDetail', 
        query: { 
            id: id,
            employeeName: employeeName,
            assessmentStatus: assessmentStatus
        } 
    })
}

onMounted(() => {
    // 可以在这里添加其他初始化逻辑
})
</script>

<style scoped>
.page-card {
    max-width: 1100px;
    margin: 32px auto;
    padding: 32px 24px;
    background: #f8fafc;
    border-radius: 16px;
    border: none;
}

.detail-header {
    display: flex;
    align-items: center;
    margin-bottom: 24px;
}

.detail-title {
    font-size: 24px;
    font-weight: 700;
    margin: 0;
}

.filter-bar {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
}

.search-input {
    flex: 1;
}

.ml-2 {
    margin-left: 8px;
}

.mr-2 {
    margin-right: 8px;
}

.mt-2 {
    margin-top: 16px;
}

.pagination-bar {
    display: flex;
    justify-content: flex-end;
    margin-top: 24px;
}

@media (max-width: 900px) {
    .page-card {
        padding: 16px 4px;
    }

    .detail-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 8px;
    }

    .filter-bar {
        flex-direction: column;
        gap: 8px;
    }
}
</style> 